package cn.rengy.util.web;

import cn.rengy.auth.UserContextHolder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;

import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

public class RequestUtil {

    private static final Map<String,String> keyMapping=new HashMap<String,String>(2,1);
    static {
        keyMapping.put("initResourceSql", "select_all_sysResourceUri_gateway");

    }

    public static String getString(String key){
        return keyMapping.get(key);
    }

    public static String getUserAgent(Object request){
        ServerWebExchange exchange=(ServerWebExchange)request;
        ServerHttpRequest _request=exchange.getRequest();
        return _request.getHeaders().getFirst(HttpHeaders.USER_AGENT);
    }

    public static String getHeader(Object request,String name){
        ServerWebExchange exchange=(ServerWebExchange)request;
        ServerHttpRequest _request=exchange.getRequest();
        return _request.getHeaders().getFirst(name);
    }

    public static String getClientIp(Object request){
        ServerWebExchange exchange=(ServerWebExchange)request;
        ServerHttpRequest _request=exchange.getRequest();
        //格式就是client1, proxy1, proxy2
        String ip=_request.getHeaders().getFirst("x-forwarded-for");
        if(ip!=null&&ip.length()>0){
            ip=ip.split(",")[0];
        }else {
            ip = _request.getRemoteAddress().getAddress().getHostAddress();
        }
        return ip;
    }
    public static Principal getPrincipal(){
        return UserContextHolder.get();
    }
    public static void setPrincipal(Principal principal){
        UserContextHolder.set(principal);
    }
    public static String getRequestPath(Object request){
        ServerWebExchange exchange=(ServerWebExchange)request;
        return exchange.getRequest().getURI().getPath();
    }

    public static String getRequestMethod(Object request){
        ServerWebExchange exchange=(ServerWebExchange)request;
        String path=exchange.getRequest().getURI().getPath();
        return exchange.getRequest().getMethod().name();
    }
}
